package rocketmq

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/consumer"
	"github.com/apache/rocketmq-client-go/v2/primitive"
)

var consumerIns rocketmq.PushConsumer

// RegisterRocketMqConsumer 注册rocketmq消费者
func InitConsumer(addr []string, groupName string) error {
	var err error
	consumerIns, err = rocketmq.NewPushConsumer(
		consumer.WithNameServer(addr),
		consumer.WithConsumerModel(consumer.Clustering),
		consumer.WithGroupName(groupName),
	)
	if err != nil {
		return err
	}

	return nil
}

// 消费数据
func Consumer(topic string, receiveDo func(mqMsg *primitive.MessageExt)) error {
	if consumerIns == nil {
		return errors.New("RocketMq Consumer not register")
	}

	err := consumerIns.Subscribe(topic, consumer.MessageSelector{}, func(ctx context.Context,
		msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for _, item := range msgs {
			go receiveDo(item)
		}
		// 这个相当于消费者 消息ack，如果失败可以返回 consumer.ConsumeRetryLater
		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		return err
	}

	err = consumerIns.Start()
	if err != nil {
		_ = consumerIns.Unsubscribe(topic)
		return err
	}

	time.Sleep(time.Hour)
	err = consumerIns.Shutdown()
	if err != nil {
		return fmt.Errorf("ShutDown Consumer error: %s", err.Error())
	}

	return nil
}
